import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutterflow_ui/flutterflow_ui.dart';
import 'package:hive/hive.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../dd_models/dd_hive_comment_model.dart';
import '../dd_models/dd_hive_my_style_model.dart';
import '../dd_models/dd_hive_works_model.dart';
import '../dd_models/dd_search_user_model.dart';
import 'dd_config.dart';
import 'dd_hive_service.dart';
import 'dd_http.dart';
import 'dd_other.dart';

class DDHiveDao {
  static Future initLocaData(String uid) async {
    List<HiveWorksModel>? list = await getFencingList(uid: uid, type: 1);
    if (list == null || list.length == 0) {
      Map<String, dynamic>? result = await wallSearch();
      if (result != null && result['code'] == 0) {
        List<DDSearchUserModel> users = (result['data'] as List)
            .map((json) => DDSearchUserModel.fromJson(json))
            .toList();
        List<DDSearchUserModel> users1 = List.from(users);
        List<DDSearchUserModel> users2 = List.from(users);
        await setLocaData(uid, users1);
        await setLocaViodeData(uid, users2);
      }
    }
  }

  static Future setLocaViodeData(
      String uid, List<DDSearchUserModel> userInfo) async {

    var videoJson = {
      "SabreSync/video/1.mp4":
          "🥇 Celebrating the focus and finesse of fencing today! Onward, fencers! ⚔️",
      "SabreSync/video/2.mp4":
          "🏅 Fencing: a world of resilience and determination. Let's fence with passion! 🌟",
      "SabreSync/video/3.mp4":
          "🌟 Unleash your spirit on the fencing strip today! Let's fence with flair. 🤺",
      "SabreSync/video/4.mp4":
          "🤺 En garde! Celebrating the heritage and art of fencing. Onward, fencers! ⚔️",
      "SabreSync/video/5.mp4":
          "🏆 Fencing – where every touch tells a unique story! Let's create our tales. 🌟",
      "SabreSync/video/6.mp4":
          "🥇 Precision, strategy, and determination – the heart of fencing! Let's fence! 🤺",
      "SabreSync/video/7.mp4":
          "🤺 On guard! Let's savor every moment on the fencing strip. ⚔️",
      "SabreSync/video/8.mp4":
          "🥇 Celebrating the swift and calculated moves of fencing! Onward, fencers! 🌟",
      "SabreSync/video/9.mp4":
          "🌟 Fencing – where friendship and competition intertwine! Let's fence together. 🏅"
    };
    Map<String, dynamic>? result = await mediaSearch();
    if (result != null && result['code'] == 0) {
      int count = 1;
      List<DDSearchUserModel> u = userInfo;
      for (Map<String, dynamic> data in result['data'] as List) {
        String middleThumbUrl = data['middleThumbUrl'] ?? '';
        String mediaUrl = data['mediaUrl'] ?? '';
        String mediaPath = data['mediaPath'] ?? '';
        String description = videoJson[mediaPath] ?? '';
        Random random = Random();
        int index = random.nextInt(u.length);
        DDSearchUserModel user = u[index];
        await addVidoeFencing(uid, user.userId ?? '', user.nickname ?? '',
            user.avatar ?? '', description, middleThumbUrl, mediaUrl,
            count: count);
        count = count + 1;
        u.removeAt(index);
      }
    }
  }

  static Future setLocaData(
      String uid, List<DDSearchUserModel> userInfo) async {
    var json = [
      {
        "author": "A",
        "followed_count": "1",
        "works_count": 2,
        "tags": [],
        "works": [
          {
            "title": "⚔️ En garde! Let's embrace the art of fencing today.",
            "description":
                "⚔️ Fencing: a fusion of athleticism and grace! Let's embrace it. 🤺",
            "images": "assets/images/A_1.png",
            "cover_images": ["assets/images/1.jpeg"],
            "all_images": ["assets/images/A_1.png", "assets/images/1.jpeg"]
          },
          {
            "title": "🤺 It's time to unleash your inner fencer!",
            "description":
                "🌟 The energy of fencing – where passion meets skill and strategy! 🥇",
            "images": "assets/images/A_2.png",
            "cover_images": ["assets/images/2.jpeg", "assets/images/3.jpeg"],
            "all_images": [
              "assets/images/A_2.png",
              "assets/images/2.jpeg",
              "assets/images/3.jpeg"
            ]
          }
        ]
      },
      {
        "author": "B",
        "followed_count": 1,
        "works_count": 1,
        "tags": [],
        "works": [
          {
            "title": "🏆 Fencing: where skill meets strategy.",
            "description":
                "🤺 En garde, my fellow fencers! Let's make every touch count. ⚔️",
            "images": "assets/images/B_1.png",
            "cover_images": ["assets/images/4.jpeg"],
            "all_images": ["assets/images/B_1.png", "assets/images/4.jpeg"]
          }
        ]
      },
      {
        "author": "C",
        "followed_count": 2,
        "works_count": 2,
        "tags": [],
        "works": [
          {
            "title": "🤺 Experience the elegance and precision of fencing.",
            "description":
                "🏅 It's time to unveil the elegance and strength of fencing! On guard! 🥇",
            "images": "assets/images/C_1.png",
            "cover_images": ["assets/images/5.jpeg"]
          },
          {
            "title": "⚔️ Dive into the world of foil, epee, and sabre fencing!",
            "description":
                "🥇 Celebrate the art of fencing with every lunge and parry! Onward, fencers! 🏅",
            "images": "assets/images/C_2.png",
            "cover_images": ["assets/images/6.jpeg", "assets/images/7.jpeg"]
          }
        ]
      },
      {
        "author": "D",
        "followed_count": 1,
        "works_count": 1,
        "tags": [],
        "works": [
          {
            "title":
                "🤺 Defend, attack, and score in the noble sport of fencing.",
            "description":
                "⚔️ Fencing – the art of precision and speed! Who's up for a bout? 🤺",
            "images": "assets/images/D_1.png",
            "cover_images": ["assets/images/8.jpeg"]
          }
        ]
      },
      {
        "author": "E",
        "followed_count": 2,
        "works_count": 2,
        "tags": [],
        "works": [
          {
            "title": "⚔️ Let the blades clash and the victories unfold!",
            "description":
                "🌟 Fencing: a dance of blades and strategy! Who's ready to fence? ⚔️",
            "images": "assets/images/E_1.png",
            "cover_images": ["assets/images/9.jpeg", "assets/images/10.jpeg"]
          },
          {
            "title": "🥇 Forging friendships through the sport of fencing.",
            "description":
                "🏆 Experience the noble sport of fencing today! Unleash your passion! 🤺",
            "images": "assets/images/E_2.png",
            "cover_images": ["assets/images/11.jpeg", "assets/images/12.jpeg"]
          }
        ]
      },
      {
        "author": "F",
        "followed_count": 2,
        "works_count": 2,
        "tags": [],
        "works": [
          {
            "title": "🤺 Channel your focus and train like a fencer.",
            "description":
                "🥇 On guard! Let's embrace the challenges of fencing with poise. 🌟",
            "images": "assets/images/F_1.png",
            "cover_images": ["assets/images/13.jpeg"]
          },
          {
            "title": "⚔️ Every lunge and parry tells a story.",
            "description":
                "🏆 Fencers, unite! Let's celebrate the spirit of fencing. ⚔️",
            "images": "assets/images/F_2.png",
            "cover_images": ["assets/images/14.jpeg"]
          }
        ]
      },
      {
        "author": "G",
        "followed_count": 1,
        "works_count": 1,
        "tags": [],
        "works": [
          {
            "title": "🤺 Fencing is not just a sport, it's a lifestyle.",
            "description":
                "🤺 Fencing is about determination and honor! En garde, everyone! 🥇",
            "images": "assets/images/G_1.png",
            "cover_images": ["assets/images/15.jpeg", "assets/images/16.jpeg"]
          }
        ]
      },
      {
        "author": "H",
        "followed_count": 1,
        "works_count": 1,
        "tags": [],
        "works": [
          {
            "title": "🏅 Celebrating the artistry of fencing moves.",
            "description":
                "🏅 Celebrating the speed and agility of fencing! Let's strike with precision. ⚔️",
            "images": "assets/images/H_1.png",
            "cover_images": ["assets/images/17.jpeg", "assets/images/18.jpeg"]
          }
        ]
      },
      {
        "author": "I",
        "followed_count": 1,
        "works_count": 1,
        "tags": [],
        "works": [
          {
            "title":
                "⚔️ In the heart of every fencer beats the passion for the sport.",
            "description":
                "🌟 Fencing – where camaraderie meets competition! Let's fence together. 🏅",
            "images": "assets/images/I_1.png",
            "cover_images": [
              "assets/images/19.jpeg",
              "assets/images/20.jpeg",
              "assets/images/21.jpeg"
            ]
          }
        ]
      },
      {
        "author": "J",
        "followed_count": 2,
        "works_count": 2,
        "tags": [],
        "works": [
          {
            "title": "🥂 Cheers to camaraderie forged on the fencing strip!",
            "description":
                "⚔️ The beauty of fencing lies in its precision and artistry. On guard! 🌟",
            "images": "assets/images/J_1.png",
            "cover_images": ["assets/images/22.jpeg", "assets/images/23.jpeg"]
          },
          {
            "title": "🤺 Uniting fencers from around the world.",
            "description":
                "🥇 Fencing: blending athleticism and elegance! Let's fence with finesse. 🤺",
            "images": "assets/images/J_2.png",
            "cover_images": ["assets/images/24.jpeg", "assets/images/25.jpeg"]
          }
        ]
      },
      {
        "author": "K",
        "followed_count": 1,
        "works_count": 1,
        "tags": [],
        "works": [
          {
            "title": "⚔️ The clash of blades, the spirit of competition.",
            "description":
                "🤺 En garde! Let's embark on a journey of fencing excellence. 🏆",
            "images": "assets/images/K_1.png",
            "cover_images": ["assets/images/26.jpeg"]
          }
        ]
      },
      {
        "author": "L",
        "followed_count": 2,
        "works_count": 2,
        "tags": [],
        "works": [
          {
            "title": "🤺 Staying on guard, both on and off the strip.",
            "description":
                "⚔️ It's time to crush blades on the strip! Fencing fun is here. 🥇",
            "images": "assets/images/L_1.png",
            "cover_images": ["assets/images/27.jpeg", "assets/images/28.jpeg"]
          },
          {
            "title": "🎖️ Honoring the legacy of fencing's ancient roots.",
            "description":
                "🤺 Embrace the thrill of fencing! Let's hone those skills. ⚔️",
            "images": "assets/images/L_2.png",
            "cover_images": ["assets/images/29.jpeg", "assets/images/30.jpeg"]
          }
        ]
      }
    ];
    int count = 1;
    List<DDSearchUserModel> u = userInfo;
    for (Map<String, dynamic> authorData in json) {
      String author = authorData["author"];
      String followedCount = randomNumber().toString();
      int artworkCount = authorData["works_count"];
      String tags = jsonEncode(authorData["tags"]);

      Random random = Random();
      int index = random.nextInt(u.length);
      DDSearchUserModel user = u[index];

      for (var work in authorData["works"]) {
        count = count + 1;
        String title = work["title"];
        String description = work["description"];
        String artworkImage = work["images"];
        List<String> coverImage = List<String>.from(work["cover_images"]);
        List<String> allImage = [];
        allImage.add(artworkImage);
        allImage.addAll(coverImage);
        await addFencing(
          uid,
          user.userId ?? '',
          user.nickname ?? '',
          user.avatar ?? '',
          author,
          followedCount,
          artworkCount,
          tags,
          title,
          description,
          artworkImage,
          coverImage,
          allImage,
          count: count,
          bg: getBgStyle()
        );
      }
      userInfo.removeAt(index);
    }
  }

  /// create
  static Future<String?> addFencing(
    String uid,
    String userId,
    String nickname,
    String avatarUrl,
    String author,
    String followedCount,
    int artworkCount,
    String tags,
    String title,
    String description,
    String? artworkImage,
    List<String>? coverImage,
    List<String>? allImage, {
    int count = 1,
    bool myPublish = false,
    List<Uint8List>? allImageData,
    String bg = '',
  }) async {
    try {
      String fencingid = getCurrentTimeAsId(count: count).toString();
      HiveWorksModel hiveWorksModel = HiveWorksModel(
          fencingid: fencingid,
          uid: uid,
          userId: userId,
          nickname: nickname,
          avatarUrl: avatarUrl,
          author: author,
          followedCount: followedCount,
          artworkCount: artworkCount,
          tags: tags,
          title: title,
          description: description,
          artworkImage: artworkImage,
          coverImage: coverImage,
          likes: randomNumber(),
          allImage: allImage,
          myPublish: myPublish,
          type: 1,
          allImageData: allImageData,
          myBlock: false,
          bgStyle: bg);
      final hiveService = HiveService();
      Box<HiveWorksModel> box = await hiveService.box<HiveWorksModel>();
      final existList = box.values
          .where((e) => e.fencingid == hiveWorksModel.fencingid)
          .toList();
      if (existList.isNotEmpty) {
        await box.deleteAll(existList.map((e) => e.fencingid));
      }
      await box.put(hiveWorksModel.fencingid, hiveWorksModel);
      return fencingid;
    } catch (e) {
      debugPrint(e.toString());
      return null;
    }
  }

  /// create
  static Future<String?> addVidoeFencing(
    String uid,
    String userId,
    String nickname,
    String avatarUrl,
    String description,
    String middleThumbUrl,
    String mediaUrl, {
    int count = 1,
    bool myPublish = false,
  }) async {
    try {
      String fencingid = getCurrentTimeAsId(count: count).toString();
      HiveWorksModel hiveWorksModel = HiveWorksModel(
          fencingid: fencingid,
          uid: uid,
          userId: userId,
          nickname: nickname,
          avatarUrl: avatarUrl,
          description: description,
          middleThumbUrl: middleThumbUrl,
          mediaUrl: mediaUrl,
          type: 2,
          likes: randomNumber(),
          myPublish: myPublish,
          myBlock: false);
      final hiveService = HiveService();
      Box<HiveWorksModel> box = await hiveService.box<HiveWorksModel>();
      final existList = box.values
          .where((e) => e.fencingid == hiveWorksModel.fencingid)
          .toList();
      if (existList.isNotEmpty) {
        await box.deleteAll(existList.map((e) => e.fencingid));
      }
      await box.put(hiveWorksModel.fencingid, hiveWorksModel);
      return fencingid;
    } catch (e) {
      debugPrint(e.toString());
      return null;
    }
  }

  static Future<List<HiveWorksModel>?> getFencingList(
      {required String uid, required int type}) async {
    try {
      final hiveService = HiveService();
      Box<HiveWorksModel> box = await hiveService.box<HiveWorksModel>();
      Map<dynamic, HiveWorksModel> map = box.toMap();
      List<HiveWorksModel>? message = [];
      map.forEach((key, e) {
        if (e.uid == uid && e.type == type && e.myBlock == false) {
          message.add(e);
        }
      });
      return message;
    } catch (e) {
      return null;
    }
  }

  static Future<List<HiveWorksModel>?> getUserFencingList(
      {required String uid, required String userId}) async {
    try {
      final hiveService = HiveService();
      Box<HiveWorksModel> box = await hiveService.box<HiveWorksModel>();
      Map<dynamic, HiveWorksModel> map = box.toMap();
      List<HiveWorksModel>? message = [];
      map.forEach((key, e) {
        if (e.uid == uid && e.userId == userId && e.type != 2) {
          message.add(e);
        }
      });
      return message;
    } catch (e) {
      return null;
    }
  }

  static Future<List<HiveCommentModel>> getFencingCommentList(
      {required HiveWorksModel hiveWorksModel}) async {
    try {
      final hiveService = HiveService();
      Box<HiveWorksModel> box = await hiveService.box<HiveWorksModel>();
      Map<dynamic, HiveWorksModel> map = box.toMap();
      List<HiveCommentModel> message = [];
      map.forEach((key, value) async {
        if (value.fencingid == hiveWorksModel.fencingid) {
          message = value.messageList ?? [];
        }
      });
      return message;
    } catch (e) {
      return [];
    }
  }

  static Future<List<HiveCommentModel>> getFencingVideoCommentList(
      {required HiveWorksModel hiveWorksModel}) async {
    try {
      final hiveService = HiveService();
      Box<HiveWorksModel> box = await hiveService.box<HiveWorksModel>();
      Map<dynamic, HiveWorksModel> map = box.toMap();
      List<HiveCommentModel> message = [];
      map.forEach((key, value) async {
        if (value.fencingid == hiveWorksModel.fencingid) {
          message = value.videoMessageList ?? [];
        }
      });
      return message;
    } catch (e) {
      return [];
    }
  }

  static Future updateFencingComment(
      {required String fencingid,
      required String name,
      required String uid,
      required int type,
      required String message,
      String? iconUrl,
      String? soundUrl,
      int? soundTime}) async {
    try {
      HiveCommentModel model = HiveCommentModel();
      model.messageId = getCurrentTimeAsId();
      model.name = name;
      model.uid = uid;
      model.type = type;
      model.message = message;
      model.iconUrl = iconUrl;
      model.soundUrl = soundUrl;
      model.soundTime = soundTime;

      final hiveService = HiveService();
      Box<HiveWorksModel> box = await hiveService.box<HiveWorksModel>();
      Map<dynamic, HiveWorksModel> map = box.toMap();

      map.forEach((key, e) {
        if (key == fencingid) {
          e.messageList ??= [];
          e.messageList?.add(model);
        }
      });
      HiveWorksModel? worksModel = map[fencingid];
      await box.put(fencingid, worksModel!);
    } catch (e) {
      debugPrint(e.toString());
    }
  }

  static Future updateFencingCommentMyLike(
      {required String fencingid,
      required String messageId,
      required bool myLike}) async {
    try {
      final hiveService = HiveService();
      Box<HiveWorksModel> box = await hiveService.box<HiveWorksModel>();
      Map<dynamic, HiveWorksModel> map = box.toMap();
      map.forEach((key, e) {
        if (key == fencingid) {
          e.messageList ??= [];
          for (int i = 0; i < e.messageList!.length; i++) {
            if (e.messageList![i].messageId == messageId) {
              e.messageList![i].myLikes = myLike;
            }
          }
        }
      });
      HiveWorksModel? worksModel = map[fencingid];
      await box.put(fencingid, worksModel!);
    } catch (e) {
      debugPrint(e.toString());
    }
  }

  static Future updateFencingLikes(
      {required HiveWorksModel hiveWorksModel}) async {
    try {
      final hiveService = HiveService();
      Box<HiveWorksModel> box = await hiveService.box<HiveWorksModel>();
      Map<dynamic, HiveWorksModel> map = box.toMap();
      map.forEach((key, value) async {
        if (value.fencingid == hiveWorksModel.fencingid) {
          value.likes = (value.likes ?? 0) + 1;
          bool myLike = true;
          if (value.myLikes != null) {
            myLike = !value.myLikes!;
          }
          value.myLikes = myLike;
          await box.put(key, value);
        }
      });
    } catch (e) {
      debugPrint(e.toString());
    }
  }

  static Future updateFencingFollow(
      {required HiveWorksModel hiveWorksModel, required bool myFollow}) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      String cureenUid = await prefs.getString(DDKey.cureenUid) ?? '';
      final hiveService = HiveService();
      Box<HiveWorksModel> box = await hiveService.box<HiveWorksModel>();
      Map<dynamic, HiveWorksModel> map = box.toMap();
      map.forEach((key, value) async {
        if (value.userId == hiveWorksModel.userId && value.uid == cureenUid) {
          value.myFollow = myFollow;
          await box.put(key, value);
        }
      });
    } catch (e) {
      debugPrint(e.toString());
    }
  }

  static Future updateFencingBlock(
      {required HiveWorksModel hiveWorksModel, required bool myBlock}) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      String cureenUid = await prefs.getString(DDKey.cureenUid) ?? '';
      final hiveService = HiveService();
      Box<HiveWorksModel> box = await hiveService.box<HiveWorksModel>();
      Map<dynamic, HiveWorksModel> map = box.toMap();
      map.forEach((key, value) async {
        if (value.userId == hiveWorksModel.userId && value.uid == cureenUid) {
          value.myBlock = myBlock;
          await box.put(key, value);
        }
      });
    } catch (e) {
      debugPrint(e.toString());
    }
  }

  static Future<List<HiveWorksModel>?> getMyFencingList(
      {required String uid, int? type = 1}) async {
    try {
      final hiveService = HiveService();
      Box<HiveWorksModel> box = await hiveService.box<HiveWorksModel>();
      Map<dynamic, HiveWorksModel> map = box.toMap();
      List<HiveWorksModel>? message = [];
      map.forEach((key, e) {
        if (e.uid == uid &&
            // e.type == type &&
            e.myBlock == false &&
            e.myPublish == true) {
          message.add(e);
        }
      });
      return message;
    } catch (e) {
      return null;
    }
  }

  static Future<List<HiveWorksModel>?> getMyFollowList(
      {required String uid, int? type = 1}) async {
    try {
      final hiveService = HiveService();
      Box<HiveWorksModel> box = await hiveService.box<HiveWorksModel>();
      Map<dynamic, HiveWorksModel> map = box.toMap();
      List<HiveWorksModel>? message = [];
      map.forEach((key, e) {
        if (e.uid == uid &&
            // e.type == type &&
            e.myFollow == true &&
            e.myPublish == false &&
            e.myBlock != true) {
          message.add(e);
        }
      });
      return message;
    } catch (e) {
      return null;
    }
  }

  static Future<List<HiveWorksModel>?> getMyBlockList(
      {required String uid, int? type = 1}) async {
    try {
      final hiveService = HiveService();
      Box<HiveWorksModel> box = await hiveService.box<HiveWorksModel>();
      Map<dynamic, HiveWorksModel> map = box.toMap();
      List<HiveWorksModel>? message = [];
      map.forEach((key, e) {
        if (e.uid == uid && e.type == type && e.myBlock == true) {
          message.add(e);
        }
      });
      return message;
    } catch (e) {
      return null;
    }
  }

  static Future<List<HiveWorksModel>?> removeMyArticles(
      {required String fencingid}) async {
    try {
      final hiveService = HiveService();
      Box<HiveWorksModel> box = await hiveService.box<HiveWorksModel>();
      Map<dynamic, HiveWorksModel> map = box.toMap();

      map.forEach((key, value) {
        if (value.fencingid == fencingid) {
          box.delete(key);
        }
      });
      return box.values.toList();
    } catch (e) {
      return null;
    }
  }


  static Future<List<HiveMyStyleModel>?> getMyBgList()async {
    try {
      final prefs = await SharedPreferences.getInstance();
      String uid = await prefs.getString(DDKey.cureenUid) ?? '';
      final hiveService = HiveService();
      Box<HiveMyStyleModel> box = await hiveService.box<HiveMyStyleModel>();
      Map<dynamic, HiveMyStyleModel> map = box.toMap();
      List<HiveMyStyleModel>? list = [];
      map.forEach((key, e) {
        if (e.uid == uid) {
          list.add(e);
        }
      });
      return list;
    } catch (e) {
      return null;
    }
  }

  static Future<bool> addMyBg(
      {required String bg}) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      String cureenUid = await prefs.getString(DDKey.cureenUid) ?? '';
      final hiveService = HiveService();
      Box<HiveMyStyleModel> box = await hiveService.box<HiveMyStyleModel>();
      Map<dynamic, HiveMyStyleModel> map = box.toMap();
      if (map.isEmpty) {
        HiveMyStyleModel newStyle = HiveMyStyleModel(
          uid: cureenUid,
          myStyle: [bg],
        );
        await box.add(newStyle);
        return true;
      } else {
        map.forEach((key, value) async {
          if (value.uid == cureenUid) {
            value.myStyle.add(bg);
            await box.put(key, value);
          }
        });
        return true;
      }
    } catch (e) {
      return false;
    }
  }


}


